package com.xunua.webrtcdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.xunua.webrtcdemo.databinding.ActivityVideoChatBinding;
import com.xunua.webrtcdemo.utils.PermissionUtil;
import com.xunua.webrtcdemo.utils.Utils;
import com.xunua.webrtcdemo.webRtc.WebRtcManager;

import org.webrtc.EglBase;
import org.webrtc.MediaStream;
import org.webrtc.RendererCommon;
import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoTrack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VideoChatActivity extends AppCompatActivity {
    private static final String TAG = "xunyou";
    private ActivityVideoChatBinding mBinding;
    private WebRtcManager mWebRtcManager;
    private EglBase mRootEglBase;
    private String mRoomId;
    private VideoTrack mLocalVideoTrack;//本地的视频轨道
    private List<String> mPersons = new ArrayList<>();//房间里所有ID列表
    private Map<String,SurfaceViewRenderer> mVideoViews =new HashMap<>();//房间里所有ID列表对应的view

    public static void startActivity(Activity activity,String roomId){
        Intent intent = new Intent(activity,VideoChatActivity.class);
        intent.putExtra("roomId",roomId);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding=ActivityVideoChatBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        mRoomId=getIntent().getStringExtra("roomId");
        mWebRtcManager=WebRtcManager.getInstance();
        initView();
    }

    private void initView() {
        mRootEglBase=EglBase.create();
        if (!PermissionUtil.isNeedRequestPermission(this)) {
            mWebRtcManager.joinRoom(this,mRoomId,mRootEglBase);
        }
    }

    /**
     * 本地的视频流
     * @param stream
     * @param userId
     */
    public void onSetLocalStream(MediaStream stream,String userId){
        //总流
        if (stream.videoTracks.size()>0){
            mLocalVideoTrack = stream.videoTracks.get(0);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                addView(userId,stream);
            }
        });
    }

    /**
     * 远端的视频流
     * @param mediaStream
     * @param userId
     */
    public void onAddRoomStream(MediaStream mediaStream, String userId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "onAddRoomStream  run:   userId:"+userId);
                addView(userId,mediaStream);
            }
        });
    }

    private void addView(String userId, MediaStream stream) {
        //使用SurfaceViewRenderer创建SurfaceView
        SurfaceViewRenderer surfaceViewRenderer = new SurfaceViewRenderer(this);
        //初始化SurfaceViewRenderer
        surfaceViewRenderer.init(mRootEglBase.getEglBaseContext(),null);
        //设置缩放模式
        surfaceViewRenderer.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT);
        //设置视频流是否应该水平镜像
        surfaceViewRenderer.setMirror(true);

        //关联
        if (stream.videoTracks.size() > 0) {
            stream.videoTracks.get(0).addSink(surfaceViewRenderer);
        }
        mVideoViews.put(userId, surfaceViewRenderer);
        mPersons.add(userId);
        mBinding.chatVideoView.addView(surfaceViewRenderer);
        int size = mVideoViews.size();
        for (int i = 0; i < size; i++) {
//            surfaceViewRenderer  setLayoutParams
            String peerId = mPersons.get(i);
            SurfaceViewRenderer renderer1 = mVideoViews.get(peerId);

            if (renderer1 != null) {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                layoutParams.height = Utils.getWidth(this, size);
                layoutParams.width = Utils.getWidth(this, size);
                layoutParams.leftMargin = Utils.getX(this, size, i);
                layoutParams.topMargin = Utils.getY(this, size, i);
                renderer1.setLayoutParams(layoutParams);
            }
        }
    }
}